<?php
namespace admin\action;

use herosphp\bean\Beans;
use herosphp\core\Loader;
use herosphp\exception\UnSupportedOperationException;
use herosphp\http\HttpRequest;
use herosphp\utils\AjaxResult;

/**
 * grade action
 * @package admin\action
 * @author yangjian<yangjian102621@gmail.com>
 */
class GradeAction extends CommonAction {

    protected $serviceBean = 'product.grade.service';
    protected $actionTitle = '牌号';

    //数据列表页面
    public function index( HttpRequest $request ) {

        $name = $request->getParameter('name', 'trim');
        $typeid = $request->getParameter('typeid', 'trim');
        $status = $request->getParameter('status', 'trim');

        if ( $status === '' ) {
            $status = '-1';
            $request->addParameter('status', '-1');
        }
        $conditions = array();
        if ( $name ) $conditions['name'] = "%{$name}%";
        if ( $typeid ) $conditions['typeid'] = $typeid;
        if ( $status != '-1' ) $conditions['status'] = $status;

        $this->setConditions($conditions);

        //加载分类，品名，厂家
        $this->assign('types', Loader::model('productType')->where(array('status' => 1))->limit(0, 10000)->find() );
        $this->assign('brands', Loader::model('brand')->where(array('status' => 1))->limit(0, 10000)->find() );
        $this->assign('factorys', Loader::model('factory')->where(array('status' => 1))->limit(0, 10000)->find() );

        $this->assign('tableHeader', array('牌号名称','品名','厂家名称','塑料种类', '审核状态', '提交来源','提交人', '审核人', '牌号状态'));
        if ( $request->getParameter('__export') == 1 ) {
            $this->export($request);

        } else { //加载视图

            parent::index($request);

            $newItems=array();

            foreach($this->getTemplateVar('items') as $item){

                $item['from_name']=$this->getFromName($item['from']);

                if($item['submiter_name']==''){

                    $item['submiter_name']=$item['saas_user_name'];

                }else{

                    $item['submiter_name']=$item['submiter_name'];
                }

                $newItems[]=$item;
            }
            $this->assign('items', $newItems);

            $this->setView('product/grade_index');
            $this->assign("title", $this->actionTitle."列表");
            $this->assign('breadcrumb', array('产品管理',$this->getTemplateVar('title')));
            $this->assign('breadUrl', array('javascript:;','javascript:;'));
        }

    }

    /**
     * 根据from key，获取来源名
     * @param $key
     */
    public function getFromName($key=1){

       $arr=array('1'=>'saas管理后台','2'=>'报价应用');

       return $arr[$key];
    }

    //数据添加页面
    public function add(HttpRequest $request) {
        throw new UnSupportedOperationException('暂时不支持该操作.');
    }

    //数据编辑页面
    public function edit(HttpRequest $request) {
        $id = $request->getParameter('id', 'intval');
        if ( $id <= 0 ) {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, self::NO_RECORDS);
        }
        $service = Beans::get($this->getServiceBean());
        $item = $service->getItem($id);
        if ( empty($item) ) {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, self::NO_RECORDS);
        }
        AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS, null, $item);
    }

    //插入数据操作
    public function insert(HttpRequest $request) {

        $data = $request->getParameter('data');
        $data['submiter'] = $this->loginUser->getId();
        if ( $data['ischecked'] != 0 ) {
            $data['checker'] = $this->loginUser->getId();
            $data['checktime'] = date('Y-m-d H:i:s');
        }
        parent::__insert($data);
    }

    //更新数据操作
    public function update(HttpRequest $request) {

        $data = $request->getParameter('data');
        $id = $request->getParameter('id', 'intval');
        parent::__update($data, $id);

    }

    //审核，取消审核
    public function check(HttpRequest $request) {
        $id = $request->getParameter('id', 'intval');
        $check = $request->getParameter('check', 'intval');
        if ( $id <= 0 ) {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, self::NO_RECORDS);
        }
        $service = Beans::get($this->getServiceBean());
        $data = array(
            'ischecked' => $check,
            'checker' => $this->loginUser->getId(),
            'checktime' => date('Y-m-d H:i:s')
        );
        if ( $service->update($data, $id) ) {
            AjaxResult::ajaxSuccessResult();
        } else {
            AjaxResult::ajaxFailtureResult();
        }
    }

    //导出数据
    protected function export(HttpRequest $request) {
        if( $request->getParameter('__export') == 1 ){
            $ids = $request->getParameter('ids');
            if( $ids ){
                $conditions['id']['$in']=$ids;
                $this -> setConditions($conditions);
            }
            $this->setPagesize(getConfig('export_max_count'));
            $service = Beans::get($this->getServiceBean());
            $items = $service->where($this->getConditions())->limit(1, $this->getPagesize())->sort(array('addtime' => -1))->find();
            $excel = array();
            foreach($items as $k => $v)
            {
                $tmp = array();
                $tmp[] = $v["name"];
                $tmp[] = $v["brand"];
                $tmp[] = $v["factory"];
                $tmp[] = $v["typename"];
                if ( $v['ischecked'] == 0 ) {
                    $tmp[] = '未审核';
                } elseif ( $v['ischecked'] == 1 ) {
                    $tmp[] = '已通过';
                } else {
                    $tmp[] = '不通过';
                }
                $tmp[] = $v['submiter_name'];
                $tmp[] = $v['checker_name'];
                $tmp[] = $v['status'] == 1 ? '启用' : '禁用';
                $excel[] = $tmp;
            }
            $header = $this->getTemplateVar('tableHeader');
            phpexcel("牌号列表",$header,$excel);
            exit();
        }
    }

    //导入牌号
    public function import(HttpRequest $request) {

        set_time_limit(0);	//执行不超时
        $file = $_FILES['src']['tmp_name'];
        if ( !file_exists($file) ) {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, '文件上传失败！');
        }
        $headers = array(
            'A' => 'name', //牌号名称
            'B' => 'brand', //品名
            'C' => 'factory', //厂家名称
            'D' => 'type', //分类名称
            'E' => 'ischecked', //审核状态
            'F' => 'status', //牌号状态
        );
        $items = excelReader($file, $headers, $errormsg);
        if ( !empty($items) ) {
            $gradeService = Beans::get($this->getServiceBean());
            $brandService = Beans::get('product.brand.service');
            $factoryService = Beans::get('product.factory.service');
            $typeService = Beans::get('product.productType.service');
            $message = array();
            $i = 0;
            foreach ( $items as $val ) {
                $tmp = array('name' => $val['name']);
                if ( $gradeService->count(array('name' => $val['name'])) > 0 ) {
                    $message[] = "导入【{$val['name']}】失败， 已经存在 <br>";
                    continue;
                }
                $brand = $brandService->getItem(array('name' => $val['brand']));
                if ( $brand == false ) {
                    $message[] = "导入【{$val['name']}】失败， 品名{$val['brand']}不存存在 <br>";
                    continue;
                }
                $tmp['brandid'] = $brand['id'];
                $factory = $factoryService->getItem(array('name' => $val['factory']));
                if ( $factory == false ) {
                    $message[] = "导入【{$val['name']}】失败， 厂家{$val['factory']}不存存在 <br>";
                    continue;
                }
                $tmp['facid'] = $factory['id'];
                $type = $typeService->getItem(array('name' => $val['type']));
                if ( $type == false ) {
                    $message[] = "导入【{$val['name']}】失败， 分类{$val['type']}不存存在 <br>";
                    continue;
                }
                $tmp['typeid'] = $type['id'];
                if ( $val['ischecked'] == '不通过' ) $tmp['ischecked'] = -1;
                if ( $val['ischecked'] == '已通过' ) $tmp['ischecked'] = 1;
                if ( $val['ischecked'] == '未审核' ) $tmp['ischecked'] = 0;

                if ( $val['status'] == '启用' ) $tmp['status'] = 1;
                if ( $val['status'] == '禁用' ) $tmp['status'] = 0;

                $tmp['addtime'] = date('Y-m-d H:i:s');
                $tmp['updatetime'] = $tmp['addtime'];
                $tmp['submiter'] = $this->loginUser->getId();
                if ( $tmp['ischecked'] != 0 ) {
                    $tmp['checker'] = $this->loginUser->getId();
                    $tmp['checktime'] = $tmp['addtime'];
                }
                $gradeService->add($tmp);
                $i++;
            }

            $m = "成功导入牌号 {$i} 条 <br>";
            if ( !empty($message) ) {
                $m .= implode('', $message);
            }
            AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS, $m);
        } else {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, $errormsg);
        }
    }
}
